﻿using System;
using System.Data;
using System.Linq;
using AccessControl.Business;
using AccessControl.Common.Enumerations;
using AccessControl.SecurityMonitoring.FingerService;
using AccessControl.SecurityMonitoring.Properties;
using AccessControl.Utility.EnumHelper;
using AccessControl.Utility.Tools;
using DevExpress.XtraEditors;

namespace AccessControl.SecurityMonitoring.Form
{
    public partial class AddGuest : XtraForm
    {

        #region Field

        private Utility.Grid.CheckMarkSelection _checkMarkSelection;

        private const string _emptyField = "اطلاعات را وارد نمایید";
        private Boolean isSelectedPersonGuest = true;
        private readonly Common.AccessControlDS.tblPersonRow _personRow;

        #endregion

        #region Constructor

        public AddGuest(Common.AccessControlDS.tblPersonRow row)
        {
            InitializeComponent();
            _personRow = row;
            if (_personRow.PersonTitle != (int)PersonTitleConstants.Guest)
            {
                isSelectedPersonGuest = false;
                textEditFirstName.Text = string.Empty;
                textEditFirstName.Enabled = false;
                textEditLastName.Text = string.Empty;
                textEditLastName.Enabled = false;
            }
            else
            {
                isSelectedPersonGuest = true;
                textEditFirstName.Enabled = true;
                textEditLastName.Enabled = true;
            }
            textEditFirstName.Text = _personRow.PersonFirstName;
            textEditLastName.Text = _personRow.PersonLastName;
        }

        #endregion

        #region Private Method

        private void FillGridData()
        {
            var tbl = EventBusiness.SelectAll();
            if (tbl != null)
                accessControlDS.tblEvent.Merge(tbl);
            accessControlDS.AcceptChanges();
        }

        private void LoadDefaultData()
        {
            faDatePickerAccessStart.SelectedDateTime = DateTime.Now;
            faDatePickerAccessEnd.SelectedDateTime = DateTime.Now;

            comboBoxEditAccessProcedure.Properties.Items.AddRange(typeof(AccessProcedureConstants).ToStringList());
        }

        private Boolean CheckRequieredFields()
        {

            var isValid = true;
            errorProvider.Clear();
            //if (buttonEditPkPerson.Text == String.Empty)
            //{
            //    isValid = false;
            //    errorProvider.SetError(buttonEditPkPerson, _emptyField);
            //}
            if (isSelectedPersonGuest && (textEditFirstName.Text == String.Empty))
            {
                isValid = false;
                errorProvider.SetError(textEditFirstName, _emptyField);
            }
            if (isSelectedPersonGuest && (textEditLastName.Text == String.Empty))
            {
                isValid = false;
                errorProvider.SetError(textEditLastName, _emptyField);
            }
            if (memoEditDescription.Text == String.Empty)
            {
                isValid = false;
                errorProvider.SetError(memoEditDescription, _emptyField);
            }
            if (!faDatePickerAccessStart.SelectedDateTime.HasValue)
            {
                isValid = false;
                errorProvider.SetError(faDatePickerAccessStart, _emptyField);
            }
            if (!faDatePickerAccessEnd.SelectedDateTime.HasValue)
            {
                isValid = false;
                errorProvider.SetError(faDatePickerAccessEnd, _emptyField);
            }

            if (comboBoxEditAccessProcedure.Text == String.Empty)
            {
                isValid = false;
                errorProvider.SetError(comboBoxEditAccessProcedure, _emptyField);
            }
            if (_checkMarkSelection.selection.Count < 1)
            {
                isValid = false;
                errorProvider.SetError(gridControlEvent, _emptyField);
            }

            return isValid;
        }

        private static void WriteLog(String message, String callerMethod, eventLevelConstants level)
        {
            LogFile.WriteLog(LogFile.DefaultLogfileLocation + "Security Monitoring\\" + DateTime.Now.Date.ToString("yyyyMMdd") + " " + "AddGuest " + callerMethod + ".txt", level, message);
        }

        private void LoadPreviousData()
        {
            var tblPersonEventDataTable = PersonEventBuisness.SelectByFilter(String.Format("fkPerson='{0}'", _personRow.pkPerson));
            if (tblPersonEventDataTable == null)
                return;
            foreach (var row in tblPersonEventDataTable)
            {
                faDatePickerAccessStart.SelectedDateTime = row.AccessStart;
                faDatePickerAccessEnd.SelectedDateTime = row.AccessEnd;
                memoEditDescription.Text = row.AccessReason;
                comboBoxEditAccessProcedure.EditValue = row.AccessProcedure;
                comboBoxEditAccessProcedure.Text =
                    ((AccessProcedureConstants) row.AccessProcedure).GetDescription();
                _checkMarkSelection.SelectRow(
                    gridViewEvent.GetRowHandle(
                        accessControlDS.tblEvent.Rows.IndexOf(
                            accessControlDS.tblEvent.FindBypkEvent(row.fkEvent))), true);

            }

        }

        #endregion

        #region Event Handler

        private void AddGuest_Load(object sender, EventArgs e)
        {


            LoadDefaultData();
            FillGridData();
            gridControlEvent.ForceInitialize();
            _checkMarkSelection = new Utility.Grid.CheckMarkSelection(gridViewEvent);
            LoadPreviousData();
        }

        private void simpleButtonSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (!CheckRequieredFields())
                    return;
                if (isSelectedPersonGuest)
                {
                    var guestRow = accessControlDS.tblGuest.NewtblGuestRow();
                    guestRow.fkPerson = _personRow.pkPerson;
                    guestRow.GuestFirstName = textEditFirstName.Text;
                    guestRow.GuestLastName = textEditLastName.Text;
                    guestRow.Description = memoEditDescription.Text;
                    GuestBusiness.Insert(guestRow);
                    var personRow = PersonBusiness.SelectByFilter(String.Format("pkPerson LIKE '{0}'", _personRow.pkPerson)).Single();
                    personRow.PersonFirstName = textEditFirstName.Text;
                    personRow.PersonLastName = textEditLastName.Text;
                    PersonBusiness.Update(personRow);
                }
                PersonEventBuisness.DeleteByFKPerson(_personRow.pkPerson);
                for (int i = _checkMarkSelection.selection.Count - 1; i >= 0; i--)
                {
                    var fkEvent = (Int32)((DataRowView)_checkMarkSelection.GetSelectedRow(i))["pkEvent"];
                    var personEventRow = accessControlDS.tblPersonEvent.NewtblPersonEventRow();
                    personEventRow.fkPerson = _personRow.pkPerson;
                    personEventRow.fkEvent = fkEvent;
                    personEventRow.IsAllowed = true;
                    personEventRow.AccessReason = memoEditDescription.Text;
                    personEventRow.AccessProcedure = (Byte)comboBoxEditAccessProcedure.SelectedIndex;
                    if (faDatePickerAccessStart.SelectedDateTime != null) personEventRow.AccessStart = faDatePickerAccessStart.SelectedDateTime.Value;
                    if (faDatePickerAccessEnd.SelectedDateTime != null) personEventRow.AccessEnd = faDatePickerAccessEnd.SelectedDateTime.Value.AddDays(1);
                    PersonEventBuisness.Insert(personEventRow);
                }
                var fingerPrintEngineServerClient = new FingerPrintEngineServerClient("TcpBindingFinger");

                fingerPrintEngineServerClient.ClientCredentials.Windows.ClientCredential.Domain = Settings.Default.Domain;
                fingerPrintEngineServerClient.ClientCredentials.Windows.ClientCredential.UserName = Settings.Default.Username;
                fingerPrintEngineServerClient.ClientCredentials.Windows.ClientCredential.Password = Settings.Default.Password;
                fingerPrintEngineServerClient.Open();
                fingerPrintEngineServerClient.UpdatePesonEvent();
                fingerPrintEngineServerClient.Close();
                Close();
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, "Submit", eventLevelConstants.Error);
            }

        }

        #endregion

    }
}